﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace KPDownloadAutoTask.Common
{
    public class JsonConfigHelper
    {
        public static bool SaveJson(Dictionary<string, object> sectionInfo, string configFilePath, string configFileName = "appsettings.json")
        {
            if (sectionInfo.Count == 0)
                return false;

            try
            {
                var filePath = Path.Combine(configFilePath, configFileName);
                JObject jsonObject;

                if (File.Exists(filePath))
                {
                    using (StreamReader file = new StreamReader(filePath))
                    {
                        using (JsonTextReader reader = new JsonTextReader(file))
                        {
                            jsonObject = (JObject)JToken.ReadFrom(reader);
                        }
                    }
                }
                else
                {
                    jsonObject = new JObject();
                }

                foreach (var key in sectionInfo.Keys)
                {
                    jsonObject[key] = JObject.FromObject(sectionInfo[key]);
                }

                using (var writer = new StreamWriter(filePath))
                using (JsonTextWriter jsonwriter = new JsonTextWriter(writer)
                {
                    Formatting = Formatting.Indented,//格式化缩进
                    Indentation = 4,  //缩进四个字符
                    IndentChar = ' '  //缩进的字符是空格
                })
                {
                    jsonObject.WriteTo(jsonwriter);
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
